// pages/user/bindPhone/bindPhone.js
const md5 = require('../../../utils/md5.js')
const common = require('../../../utils/util.js')
const app = getApp()
Page({

    /**
     * 页面的初始数据
     */
    data: {
        unionID: 1,
        phone: '',
        codeTips: '获取验证码',
        isGetCode: false,
        code: ''
    },

    /**
     * 生命周期函数--监听页面加载
     */
    onLoad: function(options) {

    },

    /**
     * 生命周期函数--监听页面初次渲染完成
     */
    onReady: function() {

    },

    /**
     * 生命周期函数--监听页面显示
     */
    onShow: function() {

    },

    /**
     * 生命周期函数--监听页面隐藏
     */
    onHide: function() {

    },

    /**
     * 生命周期函数--监听页面卸载
     */
    onUnload: function() {

    },

    /**
     * 页面相关事件处理函数--监听用户下拉动作
     */
    onPullDownRefresh: function() {

    },

    /**
     * 页面上拉触底事件的处理函数
     */
    onReachBottom: function() {

    },

    phoneInput: function(e) {
        this.setData({
            phone: e.detail.value
        })
    },

    codeInput: function(e) {
        this.setData({
            code: e.detail.value
        })
    },

    getCode: function() {
        if (!(/^1\d{10}$/.test(this.data.phone))) {
            wx.showToast({
                title: '手机号有误',
                icon: 'none',
                duration: 2000
            })
            return
        }
        if (this.data.isGetCode) {
            return
        }
        const that = this
        let data = {}
        let sign = 'cds'
        let timestamp = Date.parse(new Date())
        data.timestamp = timestamp
        data = this.objKeySort(data)
        for (let i in data) {
            sign += (i + data[i])
        }
        sign += 'cds'
        sign = md5(sign)
        data.sign = sign
        data.phone = this.data.phone
        data.type = 2
        wx.request({
            url: 'https://www.meiboshi.vip/api/Sms/send_sms',
            header: {
                'content-type': 'application/x-www-form-urlencoded'
            },
            method: 'POST',
            data: data,
            success: function(res) {
                if (res.data.datas.Code == 'isv.BUSINESS_LIMIT_CONTROL') {
                    wx.showModal({
                        title: '提示',
                        content: '验证码获取次数过多，请稍后再试',
                        showCancel: false,
                        success(res) {}
                    })
                    return
                }
                wx.showToast({
                    title: '验证码已发送',
                    icon: 'success',
                    duration: 1000
                })
                let time = 60
                that.setData({
                    isGetCode: true
                })
                that.setData({
                    codeTips: time + '秒后重新获取'
                })
                let timeClock = setInterval(function() {
                    if (time > 1) {
                        time--
                        that.setData({
                            codeTips: time + '秒后重新获取'
                        })
                    } else {
                        that.setData({
                            codeTips: '获取验证码'
                        })
                        that.setData({
                            isGetCode: false
                        })
                        clearInterval(timeClock)
                    }
                }, 1000)
            }
        })
    },

    sureBind: function() {
        if (this.data.code == '') {
            wx.showToast({
                title: '请填写验证码',
                icon: 'none',
                duration: 2000
            })
            return
        }
        wx.showLoading({
            title: '登录中...',
        })
        const that = this
        let data = {}
        let sign = 'cds'
        let timestamp = Date.parse(new Date())
        if (wx.getStorageSync('userShare')) {
            data.belong_refer = wx.getStorageSync('userShare')
            data.phone = that.data.phone
            data.code = that.data.code
            data.login_type = 3
        } else {
            data.phone = that.data.phone
            data.code = that.data.code
            data.login_type = 3
        }
        data.timestamp = timestamp
        data = that.objKeySort(data)
        for (let i in data) {
            sign += (i + data[i])
        }
        sign += 'cds'
        sign = md5(sign)
        data.sign = sign
        wx.request({
            url: 'https://www.meiboshi.vip/api/Login/wx_phone_bing',
            header: {
                'content-type': 'application/x-www-form-urlencoded'
            },
            method: 'POST',
            data: data,
            success: function(res) {
                wx.hideLoading()
                wx.login({
                    success(loginRes) {
                        wx.setStorageSync('code', loginRes.code)
                    }
                })
                const data = res.data.datas
                if (res.data.code == 204) {
                    wx.showModal({
                        title: '提示',
                        content: res.data.error,
                        showCancel: false,
                        success(res) {}
                    })
                } else {
                    wx.setStorageSync('loginStatus', false)
                    wx.setStorageSync('token', data.token)
                    wx.setStorageSync("roleType", data.role_type)
                    wx.setStorageSync("storeType", data.store_type)
                    wx.setStorageSync("storeId", data.store_id)
                    wx.setStorageSync("userId", data.user_id)
                    wx.setStorageSync("userPhone", data.phone)
                    wx.setStorageSync("userInformation", data.information)
                    //注册formId
                    common.post('User/up_form_id', {
                        form_id: wx.getStorageSync('loginFormid')
                    }).then(function (res) { }).catch(function (e) { })
                    //浏览记录
                    common.post('Userbrowse/add_user_browse', {
                        type: 1,
                        client: 2
                    }).then(function(res) {}).catch(function(e) {})
                    if (data.is_unoid == 0) {
                        that.setData({
                            unionID: 0
                        })
                        wx.setStorageSync('unionID', 0)
                    } else {
                        wx.setStorageSync('unionID', 1)
                        // let pages = getCurrentPages(); //获取当前页面实例
                        // let prePage = pages[pages.length - 3]
                        // prePage.data.isLoading = false
                        // prePage.onLoad(prePage.options); //调用实例的onLoad方法重新加载数据;
                        // prePage.onShow();
                        // wx.navigateBack({
                        //     delta: 2
                        // })
                        if (data.information == 0) {
                            wx.redirectTo({
                                url: '/pages/guide/step1/step1'
                            })
                        } else {
                            if (wx.getStorageSync('prePageUrl') == '/pages/index/index' || wx.getStorageSync('prePageUrl') == '/pages/cart/cart' || wx.getStorageSync('prePageUrl') == '/pages/user/userCenter/userCenter' || wx.getStorageSync('prePageUrl') == '/pages/share/share') {
                                wx.switchTab({
                                    url: wx.getStorageSync('prePageUrl')
                                })
                            } else {
                                wx.redirectTo({
                                    url: wx.getStorageSync('prePageUrl')
                                })
                            }
                        }
                    }
                }
            }
        })
    },

    getUserInfo: function(e) {
        const that = this
        if (e.detail.errMsg == 'getUserInfo:ok') {
            wx.showLoading({
                title: '加载中',
            })
            let data = {}
            let key = wx.getStorageSync('token')
            let sign = 'cds'
            let timestamp = Date.parse(new Date())
            data.code = wx.getStorageSync('code')
            data.phone = wx.getStorageSync('userPhone')
            data.wx_sm = 1
            data.encryptedData = e.detail.encryptedData
            data.iv = e.detail.iv
            data.login_type = 3
            data.key = key
            data.timestamp = timestamp
            data = that.objKeySort(data)
            for (let i in data) {
                sign += (i + data[i])
            }
            sign += 'cds'
            sign = md5(sign)
            data.sign = sign
            wx.request({
                url: 'https://www.meiboshi.vip/api/Login/phone_unionid',
                header: {
                    'content-type': 'application/x-www-form-urlencoded'
                },
                method: 'POST',
                data: data,
                success: function(res) {
                    wx.login({
                        success(loginRes) {
                            wx.setStorageSync('code', loginRes.code)
                        }
                    })
                    const data = res.data.datas
                    if (res.data.code == 204) {
                        wx.hideLoading()
                        wx.setStorageSync('unionID', 0)
                        wx.showModal({
                            title: '提示',
                            content: '网络繁忙，请重新授权',
                            showCancel: false,
                            success(res) {}
                        })
                    } else {
                        wx.hideLoading()
                        wx.setStorageSync('unionID', 1)
                        // let pages = getCurrentPages(); //获取当前页面实例
                        // let prePage = pages[pages.length - 3]
                        // prePage.data.isLoading = false
                        // prePage.onLoad(prePage.options); //调用实例的onLoad方法重新加载数据;
                        // prePage.onShow();
                        // wx.navigateBack({
                        //     delta: 2
                        // })
                        if (wx.getStorageSync('userInformation') == 0) {
                            wx.redirectTo({
                                url: '/pages/guide/step1/step1'
                            })
                        } else {
                            if (wx.getStorageSync('prePageUrl') == '/pages/index/index' || wx.getStorageSync('prePageUrl') == '/pages/cart/cart' || wx.getStorageSync('prePageUrl') == '/pages/user/userCenter/userCenter' || wx.getStorageSync('prePageUrl') == '/pages/share/share') {
                                wx.switchTab({
                                    url: wx.getStorageSync('prePageUrl')
                                })
                            } else {
                                wx.redirectTo({
                                    url: wx.getStorageSync('prePageUrl')
                                })
                            }
                        }
                    }
                }
            })
        } else {
            wx.setStorageSync('unionID', 0)
            // let pages = getCurrentPages(); //获取当前页面实例
            // let prePage = pages[pages.length - 3]
            // prePage.data.isLoading = false
            // prePage.onLoad(prePage.options); //调用实例的onLoad方法重新加载数据;
            // prePage.onShow();
            // wx.navigateBack({
            //     delta: 2
            // })
            if (wx.getStorageSync('prePageUrl') == '/pages/index/index' || wx.getStorageSync('prePageUrl') == '/pages/cart/cart' || wx.getStorageSync('prePageUrl') == '/pages/user/userCenter/userCenter' || wx.getStorageSync('prePageUrl') == '/pages/share/share') {
                wx.switchTab({
                    url: wx.getStorageSync('prePageUrl')
                })
            } else {
                wx.redirectTo({
                    url: wx.getStorageSync('prePageUrl')
                })
            }
        }
    },

    objKeySort: function(obj) {
        let newkey = Object.keys(obj).sort()
        let newObj = {}
        for (let i = 0; i < newkey.length; i++) {
            newObj[newkey[i]] = obj[newkey[i]]
        }
        return newObj
    }
})